import Feature from 'ol/Feature'
import Polygon from "ol/geom/Polygon"
import { isArray } from '../utils/index'
import { v4 as uuidv4 } from 'uuid'

/**
 * 绘制多边形,默认配置
 * @param {*} coordinates
 */
export const polygon = (coordinates) => {
  if (!isArray(coordinates) || !coordinates.length) {
    throw Error('绘制多边形：传入参数格式错误，应传入数组')
  }
  const id = uuidv4()
  const polygon = new Feature({
    id,
    type: 'polygon',
    geometry: new Polygon([coordinates])
  })
  return {
    features: [polygon],
    ids: [id]
  }
}
/**
 * 绘制多边形，自定义配置
 * @param {*} opts.name
 * @param {*} opts.id
 * @param {*} opts.fill
 * @param {*} opts.coordinates
 */
export const addPolygon = (opts = {}) => {
  const { data: coordinates, id = uuidv4() } = opts
  if (!(coordinates instanceof Array) || !coordinates.length) {
    throw Error('绘制多边形：传入参数格式错误，应传入数组')
  }
  // 过滤属性，去除经纬度
  const property = Object.keys(opts)
    .filter(v => v !== 'data')
    .reduce((o, v) => {
      o[v] = opts[v]
      return o
    }, {})
  const polygon = new Feature({
    id,
    type: 'polygon',
    property,
    geometry: new Polygon([coordinates])
  })

  return {
    features: [polygon],
    ids: [id]
  }
}
